import React, { useState, useEffect, useRef } from 'react'
import './index.modules.scss'
import SearchView from '@/components/searchView/index'
import { baseURL } from '@/http/request'
import { cityData } from '@/components/js/addressOptions'
import { useLocation, useNavigate } from 'react-router-dom'
import {
  Space,
  Table,
  Button,
  Modal,
  Card,
  message,
  Input,
  Popconfirm,
  Pagination,
  Image,
  Form,
  Cascader,
  DatePicker,
  Upload,
  Col,
  Row
} from 'antd'
import {
  PlusOutlined,
  LeftOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons'
import {
  carOwnerInsuranceList,
  carOwnerInsuranceCreateExcel,
  carOwnerInsuranceSerach,
  carOwnerInsuranceAdd,
  carOwnerInsuranceChange,
  carOwnerInsuranceDelete
} from '@/http/api/carOwner'
import dayjs from 'dayjs'
let pageData = {
  page: 1,
  size: 10,
  total: 0,
  appid: localStorage.getItem('appid')
}
const { RangePicker } = DatePicker
let _id = ''
let typeList = [
  {
    title: '质保编号',
    type: 'inpute',
    model: 'filmNo'
  },
  {
    title: '车架号',
    type: 'inpute',
    model: 'carVIN'
  },
  {
    title: '保单号',
    type: 'inpute',
    model: 'warrantyNum'
  },
  {
    title: '产品型号',
    type: 'inpute',
    model: 'filmName'
  },
  {
    title: '车辆型号',
    type: 'inpute',
    model: 'carName'
  },
  {
    title: '产品类型',
    type: 'inpute',
    model: 'filmType'
  }
]
let selectedRowsdata = []
const App = () => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const Navigate = useNavigate()
  const location = useLocation()
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, setIsShowAdd] = useState(false)
  const [isShowDetils, setisShowDetils] = useState(false)
  const [isImgShow, setIsImgShow] = useState(false)
  const [detilsData, setDetilsData] = useState({})
  const [magnifyImg, setMagnifyImg] = useState('')
  const [fileList, setFileList] = useState([])
  const columns = [
    {
      title: '车险上传时间',
      dataIndex: 'create_time',
      align: 'center',
      render: (create_time) => {
        return <div>{dayjs(create_time).format('YYYY-MM-DD HH:mm:ss')}</div>
      }
    },
    {
      title: '投保人姓名',
      dataIndex: 'carOwnerName',
      align: 'center',
      minWidth: 2000
    },
    {
      title: '身份证号',
      dataIndex: 'identity',
      align: 'center'
    },
    {
      title: '保单号',
      dataIndex: 'warrantyNum',
      align: 'center'
    },
    {
      title: '联系方式',
      dataIndex: 'carOwnerPhone',
      align: 'center'
    },
    {
      title: '所在区域',
      dataIndex: 'region',
      align: 'center',
      render: (region) => {
        return <div>{region}</div>
      }
    },
    {
      title: '车辆品牌型号',
      dataIndex: 'carName',
      align: 'center'
    },
    {
      title: '车牌号',
      dataIndex: 'carNo',
      align: 'center'
    },
    {
      title: '车架号',
      dataIndex: 'carVIN',
      align: 'center'
    },
    {
      title: '投保产品',
      dataIndex: 'filmName',
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center'
    },
    {
      title: '保险费',
      dataIndex: 'price',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            onClick={() => {
              setisShowDetils(true)
              let changeData = { ...data }
              if (data._id) {
                setFileList(JSON.parse(changeData.imageList))
                changeData.startTime = dayjs(changeData.startTime).format(
                  'YYYY-MM-DD HH:mm:ss'
                )
                changeData.endTime = dayjs(changeData.endTime).format(
                  'YYYY-MM-DD HH:mm:ss'
                )

                changeData.pastingTime = dayjs(changeData.pastingTime).format(
                  'YYYY-MM-DD HH:mm:ss'
                )
                setDetilsData(changeData)
                form.setFieldsValue(changeData)
              }
            }}
          >
            详情
          </Button>
          <Button
            type="primary"
            onClick={() => {
              showModalAdd(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedRowsdata = selectedRows.map((item) => {
        return item._id
      })
    }
  }

  // 获取列表
  const getList = async () => {
    pageData.carOwnerId = location.state.id
    pageData.phone = location.state.phone
    const res = await carOwnerInsuranceList(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  // 点击确定修改
  const onFinish = async (data) => {
    data.startTime = dayjs(data.timeS[0]).format('YYYY-MM-DD HH:mm:ss')
    data.endTime = dayjs(data.timeS[1]).format('YYYY-MM-DD HH:mm:ss')
    data.pastingTime = dayjs(data.pastingTime).format('YYYY-MM-DD HH:mm:ss')
    delete data.timeS
    data.imageList = fileList
    data.carOwnerId = location.state.id
    data.appid = localStorage.getItem('appid')
    let res = ''
    if (_id) {
      data._id = _id
      res = await carOwnerInsuranceChange(data)
    } else {
      res = await carOwnerInsuranceAdd(data)
    }

    messageApi.success(res.data.message)
    getList()
    setIsShowAdd(false)
    _id = ''
    form.resetFields()
  }
  const showModalAdd = (value) => {
    let changeData = { ...value }
    if (value._id) {
      changeData.region = JSON.parse(changeData.region)
      setFileList(JSON.parse(changeData.imageList))
      changeData.timeS = [
        dayjs(changeData.startTime),
        dayjs(changeData.endTime)
      ]
      changeData.pastingTime = dayjs(changeData.pastingTime)
      setDetilsData(changeData)
      form.setFieldsValue(changeData)
      _id = value._id
    }
    setIsShowAdd(true)
  }

  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await carOwnerInsuranceDelete({ id: data._id })
    messageApi.success(res.data.message)
    getList()
  }
  // 导出
  const exportExcel = async () => {
    let data = {}
    if (selectedRowsdata.length == 0) {
      data = {
        id: 'all',
        carOwnerId: location.state.id
      }
    } else {
      data = {
        id: selectedRowsdata,
        carOwnerId: location.state.id
      }
    }
    const res = await carOwnerInsuranceCreateExcel(data)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = '车衣保险.xlsx'
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
  }
  // 搜索
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      appid: localStorage.getItem('appid'),
      carOwnerId: location.state.id,
      phone: location.state.phone,
      ...data
    }
    const res = await carOwnerInsuranceSerach(pageData)

    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  // 删除照片
  const deleteImgFn = (index) => {
    let imgData = [...fileList]
    imgData.splice(index, 1)
    setFileList(imgData)
  }
  const imgageChangeFn = (data) => {
    if (data.file.status == 'done') {
      setFileList([
        ...fileList,
        ...data.fileList.map((item) => {
          return item.response.image_url
        })
      ])
    }
  }
  return (
    <div>
      <Card>
        <div className="headerTitle align_center">
          <div className="align_center">
            <LeftOutlined
              onClick={() => {
                Navigate(-1)
              }}
              style={{ fontSize: '50px' }}
            ></LeftOutlined>
            <div>车主管理</div>
          </div>
          <div style={{ marginLeft: '50px' }}>
            车主姓名：{location.state.name}
          </div>
          <div style={{ marginLeft: '50px' }}>
            联系方式：{location.state.phone}
          </div>
        </div>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div className="headerButton">
          <div>
            <Button
              style={{ marginRight: '10px' }}
              type="primary"
              onClick={() => {
                setIsShowAdd(true)
                form.resetFields()
                setFileList([])
              }}
            >
              新增
            </Button>
            <Button
              type="primary"
              onClick={() => {
                exportExcel()
              }}
            >
              导出信息
            </Button>
          </div>
        </div>
        <div className="tabeleStyle">
          <Table
            rowSelection={{
              type: 'checkbox',
              ...rowSelection
            }}
            pagination={false}
            bordered
            rowKey="key"
            columns={columns}
            dataSource={dataSource}
          />
        </div>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      {/* 修改 */}
      <div>
        <Modal
          footer={[]}
          onCancel={() => {
            setIsShowAdd(false)
            form.resetFields()
            _id = ''
          }}
          open={isShowAdd}
        >
          <div className="Title center">酷德车膜电子车险卡</div>
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 7
            }}
            wrapperCol={{
              span: 16
            }}
            style={{
              maxWidth: 600
            }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item
              label="投保人："
              name="carOwnerName"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="投保人身份证号码："
              name="identity"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="投保人所在区域："
              name="region"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Cascader
                style={{
                  width: '200px'
                }}
                options={cityData}
              />
            </Form.Item>
            <Form.Item
              label="投保人联系方式："
              name="carOwnerPhone"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="投保车辆："
              name="carName"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="车牌号码："
              name="carNo"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="车辆识别码(VIN)："
              name="carVIN"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="投保产品名称："
              name="filmName"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="贴膜时间："
              name="pastingTime"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <DatePicker className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="质保编号："
              name="filmNo"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="保险费合计："
              name="price"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="保险期间："
              name="timeS"
              rules={[
                {
                  required: true,
                  message: '请选择'
                }
              ]}
            >
              <RangePicker
                showTime={{
                  format: 'HH:mm'
                }}
                format="YYYY-MM-DD HH:mm"
              />
            </Form.Item>
            <Form.Item
              label="图片："
              name="imageList"
              rules={[
                {
                  required: true,
                  message: '请选择'
                }
              ]}
            >
              <div>
                <div className="upImgBox align_center">
                  {fileList.map((item, index) => {
                    return (
                      <div className="imgBox center">
                        <img
                          style={{ width: '100%', height: '100%' }}
                          src={item}
                          alt=""
                        />
                        <div
                          className="mask center"
                          style={{ justifyContent: 'space-evenly' }}
                        >
                          <DeleteOutlined
                            onClick={() => {
                              deleteImgFn(index)
                            }}
                            style={{ fontSize: 20, color: '#FFFFFF' }}
                          />
                          <EyeOutlined
                            onClick={() => {
                              setMagnifyImg(item)
                              setIsImgShow(true)
                            }}
                            style={{ fontSize: 20, color: '#FFFFFF' }}
                          />
                        </div>
                      </div>
                    )
                  })}
                </div>
                <Upload
                  action={`${baseURL}api/uploadAvatar`}
                  listType="picture-card"
                  onChange={imgageChangeFn}
                  accept="image/png, image/jpeg"
                  showUploadList={false}
                  maxCount={1}
                >
                  <button
                    style={{
                      border: 0,
                      background: 'none'
                    }}
                    type="button"
                  >
                    <PlusOutlined />
                    <div
                      style={{
                        marginTop: 8
                      }}
                    ></div>
                  </button>
                </Upload>
              </div>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      <Modal
        open={isShowDetils}
        footer={[]}
        onCancel={() => {
          setisShowDetils(false)
        }}
      >
        <div className="detilsBox">
          <div className="Title center">酷德车膜电子质保保险卡</div>
          <Row>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保人：</span>
              <span> {detilsData.carOwnerName}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保人身份证号码：</span>
              <span> {detilsData.identity}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保人所在区域：</span>
              <span> {detilsData.region}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保人联系方式：</span>
              <span> {detilsData.carOwnerPhone}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保车辆：</span>
              <span> {detilsData.carName}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">车牌号码：</span>
              <span> {detilsData.carNo}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">车辆识别码(VIN)：</span>
              <span> {detilsData.carVIN}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle"> 投保产品名称：</span>
              <span> {detilsData.filmName}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">贴膜时间：</span>
              <span> {detilsData.pastingTime}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">剩余米数：</span>
              <span> {detilsData.product}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">保险编号：</span>
              <span> {detilsData.warrantyNum}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">保险费：</span>
              <span> {detilsData.price}</span>
            </Col>

            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">保险期间：</span>
              <span>
                {detilsData.startTime}至{detilsData.endTime}
              </span>
            </Col>
          </Row>
          <div>
            {fileList.map((item, index) => {
              return (
                <Image key={index} width={'100%'} height={200} src={item} />
              )
            })}
          </div>
        </div>
        <div className="center">
          <div
            className="footButton center"
            onClick={() => {
              setisShowDetils(false)
            }}
          >
            确定
          </div>
        </div>
      </Modal>
      {/* 图片放大效果 */}
      <Modal
        open={isImgShow}
        footer={[]}
        onCancel={() => {
          setIsImgShow(false)
        }}
        closable={false}
      >
        <div>
          <img className="ImgShow" src={magnifyImg} alt="" srcset="" />
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
}
export default App
